from src.database.connection import HospitalDatabase
import tkinter.messagebox

# Initialize database connection
db = HospitalDatabase()
if not db.connect():
    print("Failed to connect to database")
    exit()

class EmployeeBackend:
    """Backend logic for employee management"""
    
    def __init__(self):
        self.db = db
    
    def add_employee(self, employee_data):
        """Add a new employee to the database"""
        try:
            return self.db.add_medical_staff(
                staff_id=employee_data['staff_id'],
                first_name=employee_data['first_name'],
                last_name=employee_data['last_name'],
                email=employee_data['email'],
                phone=employee_data['phone'],
                specialization=employee_data['specialization'],
                dept_id=employee_data['dept_id'],
                salary=employee_data['salary'],
                license_number=employee_data.get('license_number')
            )
        except Exception as e:
            raise Exception(f"Error adding employee: {str(e)}")
    
    def update_employee(self, staff_id, update_data):
        """Update employee information"""
        try:
            return self.db.update_medical_staff(staff_id, **update_data)
        except Exception as e:
            raise Exception(f"Error updating employee: {str(e)}")
    
    def delete_employee(self, staff_id):
        """Delete an employee from the database"""
        try:
            return self.db.delete_medical_staff(staff_id)
        except Exception as e:
            raise Exception(f"Error deleting employee: {str(e)}")
    
    def get_employee(self, staff_id):
        """Get employee by ID"""
        try:
            return self.db.get_medical_staff(staff_id)
        except Exception as e:
            raise Exception(f"Error getting employee: {str(e)}")
    
    def get_all_employees(self):
        """Get all employees from database"""
        try:
            return self.db.get_all_medical_staff()
        except Exception as e:
            raise Exception(f"Error getting all employees: {str(e)}")
    
    def validate_employee_data(self, employee_data):
        """Validate employee data before saving"""
        required_fields = ['staff_id', 'first_name', 'last_name', 'email', 'phone', 'specialization', 'dept_id', 'salary']
        
        for field in required_fields:
            if not employee_data.get(field, '').strip():
                return False, f"Field '{field}' is required"
        
        # Validate email format
        email = employee_data.get('email', '').strip()
        if '@' not in email or '.' not in email:
            return False, "Invalid email format"
        
        # Validate phone number (should already be digits only from frontend)
        phone = employee_data.get('phone', '').strip()
        if not phone or len(phone) < 7 or not phone.isdigit():
            return False, "Phone number must have at least 7 digits"
        
        # Validate salary is positive
        try:
            salary = float(employee_data['salary'])
            if salary <= 0:
                return False, "Salary must be a positive number"
        except ValueError:
            return False, "Salary must be a valid number"
        
        # Validate dept_id is positive
        try:
            dept_id = int(employee_data['dept_id'])
            if dept_id <= 0:
                return False, "Department ID must be a positive number"
        except ValueError:
            return False, "Department ID must be a valid number"
        
        return True, "Valid"

